<template>
  <div class="dt-content-progress-left">
    <div class="dt-content-progress-left-in">
      <div :class="getClassName(approvalDetial)">
        <i class="el-icon-s-check"></i>
        <span>审批状态：{{ approvalDetial.auditStateName }}</span>
      </div>
      <div class="dt-content-progress-table">
        <el-table :data="tableData" border style="width: 100%" :show-header="false">
          <el-table-column prop="itemName" width="150" class-name="dt-content-progress-cell-top"> </el-table-column>
          <el-table-column prop="name">
            <template slot-scope="scope">
              <span class="dt-content-progress-cell" v-if="scope.$index == 3"
                >{{ scope.row.name }} <em v-if="approvalDetial.remainDays < 0">延期{{ Math.abs(approvalDetial.remainDays) }}天</em
                ><span style="margin-left: 10px" v-else>剩余{{ approvalDetial.remainDays }}天</span></span
              >
              <div v-else-if="scope.$index == targetIndex && approvalDetial.auditType != '0'">
                <p class="dt-content-progress-cell-file" v-for="item in scope.row.name" :key="item.id">
                  <i class="el-icon-document"></i><span :title="item.fileName">{{ item.fileName }}</span
                  ><span>{{ item.userName }}</span
                  ><span>{{ item.createTime }}</span
                  ><span><el-button type="text" @click="downLoad(item)" size="mini">下载</el-button></span>
                </p>
                <!-- {{scope.row.name}} -->
              </div>
              <div v-else-if="scope.$index == targetIndex2 && approvalDetial.auditType != '0'">
                <p>
                  <span v-if="approvalDetial.jdName">校对（{{ approvalDetial.jdName }}）</span>
                  <em v-if="approvalDetial.shName && approvalDetial.jdName">—</em>
                  <span v-if="approvalDetial.shName">审核（{{ approvalDetial.shName }}）</span>
                  <em v-if="approvalDetial.sdName && (approvalDetial.shName || approvalDetial.jdName)">—</em>
                  <span v-if="approvalDetial.sdName">审定（{{ approvalDetial.sdName }}）</span>
                </p>
              </div>
              <span class="dt-content-progress-cell" v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="dt-content-progress-form" v-if="approvalDetial.auditType != '0'">
          <el-form :model="formData" :rules="rules" ref="formData" label-width="150px" label-position="left">
            <el-form-item label="审批附件" class="dt-content-progress-file">
              <el-upload
                action="#"
                :http-request="httpRequest"
                :show-file-list="false"
                :on-change="handleChange"
                :limit="5"
                :file-list="this.formData.fileList"
                :before-upload="beforeAvatarUpload"
                :on-exceed="handleExceed"
                :disabled="approvalDetial.showButton != 1"
              >
                <el-button :disabled="approvalDetial.showButton != 1" slot="trigger" size="small" icon="el-icon-upload2">添加附件</el-button>
                <div slot="tip" class="el-upload__tip">单个文件小于10M，最多可以上传5个附件</div>
              </el-upload>
              <div v-for="item in this.formData.fileList" :key="item.uid">
                <div class="dt-content-approval-achievement">
                  <span class="dt-content-approval-filename"><i class="el-icon-document"></i>{{ item.name }}</span>
                  <span>{{ UName }}</span>
                  <span class="dt-content-approval-btn">
                    <el-button type="text" @click="handleRemove(item)">删除</el-button>
                  </span>
                </div>
                <div>
                  <el-progress v-if="item.percentage != 100" :percentage="item.percentage" :stroke-width="2"></el-progress>
                </div>
              </div>
              <div v-if="approvalDetial.auditState != 1">
                <div class="dt-content-approval-achievement" v-for="item in approvalDetial.auditFile" :key="item.id">
                  <span class="dt-content-approval-filename"><i class="el-icon-document"></i>{{ item.fileName }}</span>
                  <span>{{ item.userName }}</span>
                  <span class="dt-content-approval-btn">
                    <!-- <el-button type="text" @click="handlePreview(item,1)">预览</el-button> -->
                    <el-button type="text" @click="downLoad(item)">下载</el-button>
                  </span>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="审批意见" prop="remark" class="dt-content-progress-remark">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="formData.remark"
                maxlength="200"
                show-word-limit
                v-if="approvalDetial.auditState == 1 && approvalDetial.showButton == 1"
              >
              </el-input>
              <span style="line-height: 1.5" v-else>{{ approvalDetial.remark || '--' }}</span>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dt-content-progress-btn" v-if="approvalDetial.showButton == 1">
        <el-button type="primary" size="small" class="dt-content-progress-btn-left" @click="AuditActions('1')">通过</el-button>
        <el-button size="small" class="dt-content-progress-btn-left" @click="AuditActions('2')">拒绝</el-button>
      </div>
      <el-dialog title="" :visible.sync="isShowImage" :append-to-body="true" :before-close="closeShow">
        <el-image :src="imgSrc" fit="fill" v-if="imgSrc"></el-image>
        <iframe
          v-if="fileSrc"
          :src="`https://view.officeapps.live.com/op/view.aspx?src=${fileSrc}`"
          width="100%"
          height="800px"
          frameBorder="0"
        ></iframe>
      </el-dialog>
    </div>
  </div>
</template>
<script>
export default {
  head() {
    return {
      script: [
        {
          type: 'text/javascript',
          src: 'https://www.ccccdt.com/skb/js/oos-sdk-6.0.min.js',
          body: false
        }
      ]
    }
  },
  props: {
    approvalDetial: Object // 指定prop为Object类型
    // ProjectLogList: Array,
    // TotalRecord: Number,
    // TotalPage: Number,
    // LogTotalPage: Number,
    // LogTotalRecord: Number,
    // ActiveName: {
    //   type: [String], // 可以是字符串
    //   required: true, // 必填项
    //   default: '0' // 如果没有传递，则使用默认值
    // }
  },
  data() {
    return {
      Uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id,
      UName: decodeURIComponent(this.$store.state.uname), //用户名称,
      formData: {
        annexJson: null,
        remark: null,
        fileList: []
      },
      rules: {},
      fileSrc: '',
      imgSrc: '',
      isShowImage: false,
      targetIndex: 4,
      targetIndex2: 7
    }
  },
  computed: {
    tableData() {
      if (this.approvalDetial.auditType == '0') {
        if (this.approvalDetial.delayReason) {
          return [
            {
              itemName: '审批类型',
              name: this.approvalDetial.auditTypeName
            },
            {
              itemName: '所属项目',
              name: this.approvalDetial.rootProjectName
            },
            {
              itemName: '任务名称',
              name: this.approvalDetial.taskName
            },
            {
              itemName: '任务截止时间',
              name: this.approvalDetial.endTime ? this.approvalDetial.endTime.substring(0, 10) : '无截止时间'
            },
            {
              itemName: '延期原因',
              name: this.approvalDetial.delayReason
            },
            {
              itemName: '当前完成进度',
              name: this.approvalDetial.progress + '%'
            },
            {
              itemName: '本次完成进度',
              name: this.approvalDetial.currentProgress + '%'
            },
            {
              itemName: '发起人',
              name: this.approvalDetial.createName
            },
            {
              itemName: '提交时间',
              name: this.approvalDetial.submitTime
            },
            {
              itemName: '审批人',
              name: this.approvalDetial.auditName
            }
          ]
        } else {
          return [
            {
              itemName: '审批类型',
              name: this.approvalDetial.auditTypeName
            },
            {
              itemName: '所属项目',
              name: this.approvalDetial.rootProjectName
            },
            {
              itemName: '任务名称',
              name: this.approvalDetial.taskName
            },
            {
              itemName: '任务截止时间',
              name: this.approvalDetial.endTime ? this.approvalDetial.endTime.substring(0, 10) : '无截止时间'
            },
            {
              itemName: '当前完成进度',
              name: this.approvalDetial.progress + '%'
            },
            {
              itemName: '本次完成进度',
              name: this.approvalDetial.currentProgress + '%'
            },
            {
              itemName: '发起人',
              name: this.approvalDetial.createName
            },
            {
              itemName: '提交时间',
              name: this.approvalDetial.submitTime
            },
            {
              itemName: '审批人',
              name: this.approvalDetial.auditName
            }
          ]
        }
      } else {
        if (this.approvalDetial.delayReason) {
          this.targetIndex = 5
          this.targetIndex2 = 8
          return [
            {
              itemName: '审批类型',
              name: this.approvalDetial.auditTypeName
              // name: '审图'
            },
            {
              itemName: '所属项目',
              name: this.approvalDetial.projectName
            },
            {
              itemName: '任务名称',
              name: this.approvalDetial.taskName
            },
            {
              itemName: '任务截止时间',
              name: this.approvalDetial.endTime ? this.approvalDetial.endTime.substring(0, 10) : '无截止时间'
            },
            {
              itemName: '延期原因',
              name: this.approvalDetial.delayReason
            },
            {
              itemName: '任务成果',
              name: this.approvalDetial.taskResult
            },

            // {
            //   itemName: '当前完成进度',
            //   name: this.approvalDetial.progress
            // },
            // {
            //   itemName: '本次完成进度',
            //   name: this.approvalDetial.currentProgress
            // },
            {
              itemName: '发起人',
              name: this.approvalDetial.createName
            },
            {
              itemName: '提交时间',
              name: this.approvalDetial.submitTime
            },
            {
              itemName: '审批流程',
              name: this.approvalDetial.jdName || this.approvalDetial.shName || this.approvalDetial.sdName
            }
          ]
        } else {
          return [
            {
              itemName: '审批类型',
              name: this.approvalDetial.auditTypeName
              // name: '审图'
            },
            {
              itemName: '所属项目',
              name: this.approvalDetial.projectName
            },
            {
              itemName: '任务名称',
              name: this.approvalDetial.taskName
            },
            {
              itemName: '任务截止时间',
              name: this.approvalDetial.endTime ? this.approvalDetial.endTime.substring(0, 10) : '无截止时间'
            },
            // {
            //   itemName: '延期原因',
            //   name: this.approvalDetial.delayReason
            // },
            {
              itemName: '任务成果',
              name: this.approvalDetial.taskResult
            },

            // {
            //   itemName: '当前完成进度',
            //   name: this.approvalDetial.progress
            // },
            // {
            //   itemName: '本次完成进度',
            //   name: this.approvalDetial.currentProgress
            // },
            {
              itemName: '发起人',
              name: this.approvalDetial.createName
            },
            {
              itemName: '提交时间',
              name: this.approvalDetial.submitTime
            },
            {
              itemName: '审批流程',
              name: this.approvalDetial.jdName || this.approvalDetial.shName || this.approvalDetial.sdName
            }
          ]
        }
      }
    }
  },
  methods: {
    getClassName(item) {
      let className = ''
      switch (item.auditState) {
        case 1:
          className = 'dt-content-progress-state'
          break
        case 2:
          className = 'dt-content-progress-success'
          break
        case 3:
          className = 'dt-content-progress-refuse'
          break
        default:
          className = 'dt-content-progress-state'
          break
      }
      return className
    },
    AuditActions(handleType) {
      // 定义共同的变量
      const domain = [this.$store.state.DOMAIN]
      // 根据auditType决定路径
      let path
      let data
      if (this.approvalDetial.auditType == '0') {
        path = ['/project/taskAudit/handleAuditProgress']
        data = [{ userId: this.Uid, taskId: this.approvalDetial.taskId, handleType: handleType }]
      } else {
        this.$refs['formData'].validate((valid) => {
          if (valid) {
            path = ['/project/taskAudit/handleAuditDrawing']
            var annexJson = this.formData.fileList.map((item) => ({
              fileName: item.name,
              fileUrl: item.url,
              fileSize: item.size,
              createUid: item.createUid
            }))
            data = [
              {
                userId: this.Uid,
                taskId: this.approvalDetial.taskId,
                handleType: handleType,
                remark: this.formData.remark,
                annexJson: JSON.stringify(annexJson)
              }
            ]
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
      // 如果路径被正确设置，则执行请求
      if (path) {
        const dataAxios = this.$tools.getDataAxios(this, domain, path, data)
        Promise.all(dataAxios)
          .then((response) => {
            this.$tools.callbackAxios(this, response, (response) => {
              const data = response[0].data
              if (data.code === 200) {
                this.$message.success('操作成功')
                this.formData.fileList = []
                this.$emit('dataChange', data.data)
              } else {
                this.$message.error(data.message)
              }
            })
          })
          .catch((error) => {
            // 处理错误情况
          })
      }
    },
    downLoad(item) {
      var URL = this.$tools.getStsFileUrl(this.$store.state.uid, item.fileUrl || item.url)
      this.downloadFile(URL, item.fileName)
    },
    downloadFile(url, filename, mimeType) {
      // 如果是URL，直接创建a标签下载
      // 检查是否为同源URL
      if (new URL(url).origin != window.location.origin) {
        // 对于非同源URL，使用window.open在新标签页中打开链接
        window.open(url, '_blank')
      } else {
        // 对于同源URL，可以创建一个临时的<a>元素并模拟点击
        const a = document.createElement('a')
        a.href = url
        a.download = filename
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
    },
    // downloadFile(url, filename) {
    //   this.$axios({
    //     url: url,
    //     method: 'POST',
    //     responseType: 'blob', // 重要：需要设置响应类型为blob
    //     headers: {
    //       'Content-Type': 'application/x-www-form-urlencoded',
    //       cookie_user_id: encodeURIComponent(this.$store.state.uid || '0'),
    //       zjskauth: this.$tools.getZJSKAUTH(this.$store.state.uid || '0', this.$store.state.DOMAIN + '/project/taskAudit/handleAuditDrawing'),
    //       login_guid: this.$store.state.guid || '0'
    //     } // 添加自定义请求头
    //   })
    //     .then((response) => {
    //       // 创建一个隐藏的<a>元素用于下载
    //       const link = document.createElement('a')
    //       link.href = window.URL.createObjectURL(new Blob([response.data]))
    //       link.setAttribute('download', filename) // 设置下载的文件名
    //       document.body.appendChild(link)
    //       link.click()
    //       document.body.removeChild(link) // 下载后移除元素
    //       window.URL.revokeObjectURL(link.href) // 释放blob URL
    //     })
    //     .catch((error) => {
    //       console.error('下载文件出错:', error)
    //     })
    // },
    /* *************上传文件操作******************** */
    handleChange(file, fileList) {
      var url = 'https://www.ccccdt.com/ccccdt/' + file.raw.key
      file = {
        ...file,
        key: null,
        url: url,
        createUid: this.Uid,
        isCanReName: true,
        newFileName: ''
      }

      this.formData.fileList = [...this.formData.fileList, file]
    },
    httpRequest(req) {
      this.$tools.getStsClient(this, req.file, (state, client, bucketName, file) => {
        if (state) {
          this.uploadFile(client, bucketName, file)
        }
      })
    },

    uploadFile(client, bucketName, file) {
      var time = new Date().getTime() + '',
        key = time.split('').reverse().join('') + this.$tools.getRandomName(file)
      var params = {
        Body: file,
        Bucket: bucketName,
        Key: key,
        ContentDisposition: `attachment; filename="${encodeURIComponent(file.name)}"`
      }
      client
        .putObject(params, (err, data) => {
          if (err) {
          } else {
            this.onSuccess(file, key)
          }
        })
        .on('httpUploadProgress', (progress) => {
          this.onProgress(progress, file)
        })
    },
    onSuccess(file, key) {
      this.formData.fileList.forEach((item) => {
        if (item.uid == file.uid) {
          item.status = 'success'
          item.key = key
          item.url = 'https://www.ccccdt.com/ccccdt/' + key
        }
      })
    },
    onProgress(progress, file) {
      if (progress.lengthComputable) {
        var index = this.formData.fileList.findIndex((item) => item.uid === file.uid)
        this.formData.fileList[index].percentage = Number(((progress.loaded / progress.total) * 100).toFixed(0))
      }
    },
    handleRemove(file) {
      this.formData.fileList = this.formData.fileList.filter((item) => item.uid !== file.uid)
    },
    // handlePreview(file, type) {
    //   if (type == 1) {
    //     var suffix = file.fileName.substring(file.fileName.lastIndexOf('.') + 1)
    //     const supportedImageSuffixes = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'bmp']
    //     const officeArr = ['docx', 'xlsx', 'ppt', 'txt', 'doc', 'xls', , 'pdf', 'pptx']
    //     console.log(file)
    //     if (supportedImageSuffixes.includes(suffix)) {
    //       this.isShowImage = true
    //       this.imgSrc = this.$tools.getStsFileUrl(this.$store.state.uid, file.fileUrl)
    //     }
    //     if (officeArr.includes(suffix)) {
    //       this.isShowImage = true
    //       this.fileSrc = this.$tools.getStsFileUrl(this.$store.state.uid, file.fileUrl)
    //       console.log(this.fileSrc)
    //     }
    //   } else {
    //     var suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
    //     const supportedImageSuffixes = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'ico', 'bmp']
    //     const officeArr = ['docx', 'xlsx', 'ppt', 'txt', 'doc', 'xls', , 'pdf', 'pptx']
    //     if (supportedImageSuffixes.includes(suffix)) {
    //       this.isShowImage = true
    //       this.imgSrc = this.$tools.getStsFileUrl(this.$store.state.uid, 'https://www.ccccdt.com/ccccdt/' + file.key)
    //     }
    //     if (officeArr.includes(suffix)) {
    //       this.isShowImage = true
    //       this.fileSrc = this.$tools.getStsFileUrl(this.$store.state.uid, 'https://www.ccccdt.com/ccccdt/' + file.key)
    //     }
    //   }
    // },
    beforeAvatarUpload(file) {
      console.log(file)
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        // 找到要删除的对象的索引
        let index = this.formData.fileList.findIndex((item) => item.uid === file.uid)
        // 如果找到了对象，使用splice方法删除它
        if (index !== -1) {
          this.formData.fileList.splice(index, 1)
        }
      }
      return isLt2M
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      // if (this.formData.fileList.length > 5) {
      //   this.$message.warning(`当前限制只能选择 5 个文件`)
      // }
      // this.$message.warning()
    },
    /*************************** 文件上传结束***********************************************************/
    closeShow(done) {
      this.imgSrc = ''
      this.fileSrc = ''
      done()
    },
    validateFileList(rule, value, callback) {
      if (value.length === 0) {
        callback(new Error('文件不能为空'))
      } else {
        // 可以在这里添加更多的验证逻辑，比如检查文件类型、大小等
        callback()
      }
    }
  },

  mounted() {}
}
</script>
<style scoped>
.dt-content-progress-left {
  background-color: #fff;
  width: 66%;
  border-right: 1px solid #e9eef7;
}
.dt-content-progress-left-in {
  padding: 14px 20px 0 20px;
}
.dt-content-progress-state {
  height: 48px;
  line-height: 48px;
  background-color: #fff2e8;
  padding-left: 12px;
}
.dt-content-progress-success {
  height: 48px;
  line-height: 48px;
  background-color: #f6ffed;
  padding-left: 12px;
}
.dt-content-progress-refuse {
  height: 48px;
  line-height: 48px;
  background-color: #f2f3f5;
  padding-left: 12px;
}
.dt-content-progress-success i {
  margin-right: 8px;
  font-size: 18px;
  color: #52c41a;
}
.dt-content-progress-refuse i {
  margin-right: 8px;
  font-size: 18px;
  color: #909399;
}
.dt-content-progress-state i {
  margin-right: 8px;
  font-size: 18px;
  color: #ff7a45;
}
.dt-content-progress-success span {
  font-size: 14px;
  color: #52c41a;
}
.dt-content-progress-refuse span {
  font-size: 14px;
  color: #909399;
}
.dt-content-progress-state span {
  font-size: 14px;
  color: #ff7a45;
}
::v-deep .dt-content-progress-cell-top {
  font-size: 14px;
  color: #606266 !important;
  background-color: #fafafa;
}
.dt-content-progress-cell em {
  margin-left: 20px;
  color: #f5222d;
}
.dt-content-progress-table {
  margin-top: 8px;
}
.dt-content-progress-btn {
  margin-top: 30px;
  padding-left: 150px;
}
.dt-content-progress-btn-left {
  width: 88px;
  height: 36px;
  font-size: 14px;
}
.dt-content-progress-cell-file {
  display: flex;
  align-items: center;
  font-size: 12px;
  padding: 0 8px;
}
.dt-content-progress-cell-file:hover {
  background-color: #f0f5ff;
}
.dt-content-progress-cell-file span:nth-of-type(1) {
  /* width: 660px; */
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-left: 4px;
}
.dt-content-progress-cell-file span:nth-of-type(2) {
  /* flex: 56px; */
  width: 56px;
  margin-left: 60px;
}
.dt-content-progress-cell-file span:nth-of-type(3) {
  /* flex: 6; */
  margin-left: 60px;
}
.dt-content-progress-cell-file span:nth-of-type(4) {
  /* flex: 1; */
  width: 60px;
  margin-left: 60px;
}
.dt-content-progress-form {
  margin-top: 20px;
}
.dt-content-progress-form >>> .el-form-item__label {
  padding-left: 10px;
}
.dt-content-progress-form >>> .el-form-item__content {
  line-height: 0;
}
.el-upload__tip {
  display: inline-block;
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
  margin-top: 0 !important;
}
.dt-content-approval-achievement {
  display: flex;
  align-items: center;
}
.dt-content-approval-achievement .dt-content-approval-filename {
  flex: 1;
}
.dt-content-approval-filename .el-icon-document {
  margin-right: 4px;
}
.dt-content-approval-achievement .dt-content-approval-btn {
  margin-left: 60px;
  width: 60px;
  padding-right: 18px;
}
.dt-content-approval-achievement > span:nth-of-type(2) {
  width: 118px;
  line-height: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-left: 60px;
}
.dt-content-progress-table >>> .el-table__cell {
  padding: 8px 0;
  color: #1f1f1f;
}
::v-deep .el-progress__text {
  font-size: 12px !important;
}
.dt-content-progress-remark >>> .el-form-item__content {
  padding-top: 9px;
}
.dt-content-progress-file >>> .el-form-item__content {
  padding-top: 3.5px;
}
.dt-content-progress-table >>> .el-table__row:hover > td {
  background-color: transparent !important;
}
.dt-content-progress-table >>> .el-table__row:hover > td.dt-content-progress-cell-top {
  background-color: #fafafa !important;
}
</style>
